<?php
/**
 * Zhub - A PHP Framework For API Developer
 *
 * This file is part of the Zhub package.
 *
 * (c) YiLong Fan <fantiq@163.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author fanyilong <fantiq@163.com>
 * @copyright 2017 fanyilong. All rights reserved.
 * @package Zhub
 * @date 18-3-5
 */

namespace Zhub\HttpMessage\Headers;


use Zhub\DataStruct\Map;

class CookieMap extends Map
{
    public function get(string $key):Cookie
    {
        return $this->getBucket($key);
    }

    public function put(string $key, Cookie $cookie = null)
    {
        $this->putBucket($key, $cookie);
    }

    public function toString(): string
    {
        $setCookieKey = 'Set-' . ucfirst(strtolower(HeaderStruct::COOKIE)) . ': ';

        $cookies = $this->each(function ($key, Cookie $cookie) use ($setCookieKey) {
            $raw = [];
            $raw[] = $cookie->getKey() . '=' . $cookie->getValue();

            $path = $cookie->getPath();
            if ($path !== null) {
                $raw[] = strtolower(Cookie::PATH) . '=' . $path;
            }

            $expire = $cookie->getExpires();
            if ($expire !== null) {
                $raw[] = strtolower(Cookie::EXPIRES) . '=' . $expire;
            }

            $domain = $cookie->getDomain();
            if ($domain !== null) {
                $raw[] = strtolower(Cookie::DOMAIN) . '=' . $domain;
            }

            $httpOnly = $cookie->getHttpOnly();
            if ($httpOnly !== null) {
                $raw[] = strtolower(Cookie::HTTP_ONLY) . '=' . $httpOnly;
            }

            $secure = $cookie->getSecure();
            if ($secure !== null) {
                $raw[] = strtolower(Cookie::SECURE) . '=' . $secure;
            }

            return $setCookieKey . implode('; ', $raw);
        });
        return implode("\n", $cookies);
    }
}
